<?php

class ListController extends Controller {

    // List Brands
    public function actionIndex() {

        $data = parent::$pageData;
        if ($data['pageId'] == 1)
            $popularBrandsID = array(357, 12329, 367, 1025, 18272, 12996, 898, 1218, 12363, 736, 12832, 12415);
        elseif ($data['pageId'] == 2) {
            $popularBrandsID = array(11926, 13234, 11982, 12112, 12264, 12116, 12110, 20818, 4138, 11935, 12775, 90444);
        } elseif ($data['pageId'] == 3) {
            $popularBrandsID = array(3014, 1530, 3169, 4170, 4411, 5705, 6111, 6174, 6395, 7166, 8520, 8820);
        } elseif ($data['pageId'] == 6) {
            $popularBrandsID = array(12, 9218, 9419, 9612, 9800, 10000, 10113, 10231, 10487, 10714, 102010, 102038);
        } elseif ($data['pageId'] == 10) {
            $popularBrandsID = array(17860, 17511, 17363, 17532, 17384, 17574, 17406, 17645, 17553, 17469, 17776, 17490);
        } elseif ($data['pageId'] == 9) {
            $popularBrandsID = array(14280, 17341, 14028, 16578, 15684, 15688, 15729, 13570, 14950, 15249, 15799, 16816);
        } elseif ($data['pageId'] == 7) {
            $popularBrandsID = array(11626, 11582, 11713, 11667, 103620, 11598, 13472, 11788, 11753, 92165, 11726, 11618);
        } elseif ($data['pageId'] == 8) {
            $popularBrandsID = array(10821, 11566, 11501, 103932, 13437, 11437, 11039, 21672, 11085, 11341, 21476, 10871);
        }
        $otherBrands = array();
        if ($data['pageId'] == 1 || $data['pageId'] == 2 || $data['pageId'] == 3 || $data['pageId'] == 6 || $data['pageId'] == 10 || $data['pageId'] == 9 || $data['pageId'] == 7 || $data['pageId'] == 8) {
            $sql = "SELECT * FROM {{pages}} WHERE \"pageType\" = 'brand' AND \"pageParent\" = '{$data['pageId']}' AND \"pageActive\" = '1' AND \"pageId\" IN(" . implode(',', $popularBrandsID) . ") ORDER BY \"pageSort\", \"pageTitle\";";
            $q = "SELECT * FROM {{pages}} WHERE \"pageType\" = 'brand' AND \"pageParent\" = '{$data['pageId']}' AND \"pageActive\" = '1' AND \"pageId\" NOT IN(" . implode(',', $popularBrandsID) . ") ORDER BY \"pageSort\", \"pageTitle\";";
            $otherBrands = Yii::app()->db->getCommandBuilder()->createSqlCommand($q)->queryAll();
        } else {
            $sql = "SELECT * FROM {{pages}} WHERE \"pageType\" = 'brand' AND \"pageParent\" = '{$data['pageId']}' AND \"pageActive\" = '1' ORDER BY \"pageSort\", \"pageTitle\";";
        }
        $brands = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();

        foreach (Yii::app()->params['regions'] as $key => $value) {
            $regions[] = $value['genitive'];
        }
        $regions = implode(', ', $regions);
        if (!mb_substr_count(Controller::$pageData['pageUrl'], 'remont-kompyuterov')) {
            $this->pageTitle = isset($data['metaTitle']) && !empty($data['metaTitle']) ? $data['metaTitle'] : $data['pageTitle'] . ' в ' . $regions . ' — Моби03';
            Yii::app()->clientScript->registerMetaTag('Федеральный сервисный центр Моби03 осуществляет ' . mb_strtolower($data['pageTitle'], 'utf-8') . ' с гарантией в кратчайшие сроки. Прайс-лист на все виды работ.', 'description');
            Yii::app()->clientScript->registerMetaTag('оперативный ' . mb_strtolower($data['pageTitle'], 'utf-8') . ' с гарантией', 'keywords');
        } else {
            $this->pageTitle = $data['metaTitle'];
            Yii::app()->clientScript->registerMetaTag($data['metaDesc'], 'description');
            Yii::app()->clientScript->registerMetaTag($data['metaKeywords'], 'keywords');
        }

        $search = Page::model()->findAll("\"pageActive\" = 1 AND \"pageType\" = 'brand' AND \"pageParent\" = '{$data['pageId']}' order by \"pageTitle\"");
        $searches = [];
        $array = array();
        foreach ($search as $key => $value) {
            $searches[] = array('value' => $value['pageTitle'], 'url' => $value['pageUrl']);
            $array[$value['pageUrl']] = $value['pageTitle'];
        }
        $random = array_rand($array);

        if ($brands) {
            $this->render('index', array('datas' => $brands, 'searches' => $searches, 'array' => $array, 'random' => $random, 'otherBrands' => $otherBrands));
        } else {
            $this->render('description');
        }
    }

    // List Models
    public function actionBrand() {
        $data = parent::$pageData;
        $this->pageTitle = $data['pageTitle'];
        $criteria = new CDbCriteria();
        $criteria->compare('"pageActive"', 1);
        $criteria->compare('"pageType"', 'model');
        $criteria->compare('"pageParent"', $data['pageId']);
        $criteria->order = '"pageSort" ';
        $count = Page::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = !Yii::app()->user->isGuest && Yii::app()->user->name['userGroup'] == 'admin' && isset($_GET['sort']) ? 10000 : 20;
        $pages->applyLimit($criteria);
        $models = Page::model()->findAll($criteria);
        $search = Page::model()->findAll("\"pageActive\" = 1 AND \"pageType\" = 'model' AND \"pageParent\" = '{$data['pageId']}'");
        $array = array();
        $searches = [];
        foreach ($search as $key => $value) {
            $searches[] = array('value' => Controller::$pageData['pageTitle'] . ' ' . $value['pageTitle'], 'url' => $value['pageUrl']);
            $array[$value['pageUrl']] = Controller::$pageData['pageTitle'] . ' ' . $value['pageTitle'];
        }
        $random = array_rand($array);

        foreach (Yii::app()->params['regions'] as $key => $value) {
            $regions[] = $value['genitive'];
        }
        $regions = implode(', ', $regions);

        $replaces = array('iPhone' => 'apple', 'Apple iPad' => 'apple', 'Macbook' => 'apple', 'Apple iPod' => 'apple', 'МТС' => 'mts');

        $serrvTitle = isset($replaces[$data['pageTitle']]) ? $replaces[$data['pageTitle']] : $data['pageTitle'];

        $sql = 'SELECT "pageDescription" FROM mb_pages WHERE "pageType" = \'servcenter\' AND "pageTitle" ILIKE \'%' . pg_escape_string($serrvTitle) . '%\'';
        $relations = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();

        $this->pageTitle = isset(Controller::$pageData['metaTitle']) && !empty(Controller::$pageData['metaTitle']) ? Controller::$pageData['metaTitle'] : (Controller::$pageData['_parents']['category']['pageTitle'] . ' ' . Controller::$pageData['pageTitle'] . ' (' . (empty(Controller::$pageData['pageRussianName']) ? Controller::$pageData['pageTitle'] : Controller::$pageData['pageRussianName']) . ') в ' . $regions . ' — Моби03');

        Yii::app()->clientScript->registerMetaTag('Федеральный сервисный центр Моби03 осуществляет оперативный ' . mb_strtolower(Controller::$pageData['_parents']['category']['pageTitle'], 'utf-8') . ' ' . Controller::$pageData['pageTitle'] . ' с гарантией. Подробный прайс-лист на все виды услуг. Отзывы клиентов.', 'description');
        Yii::app()->clientScript->registerMetaTag('срочный ' . mb_strtolower(Controller::$pageData['_parents']['category']['pageTitle'], 'utf-8') . ' ' . Controller::$pageData['pageTitle'] . ' с гарантией', 'keywords');

        $this->render('brand', array('datas' => $models, 'pages' => $pages, 'searches' => $searches, 'array' => $array, 'random' => $random, 'relations' => $relations));
    }

    // model description
    public function actionModel() {
        $data = parent::$pageData;
//        $pageVisit = $data['pagevisit'] + 1;
//        $sql = 'UPDATE {{pages}} SET "pagevisit" = ' . $pageVisit . ' WHERE "pageId" = ' . $data['pageId'];
//        Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        $this->pageTitle = $data['pageTitle'];
        foreach (Yii::app()->params['regions'] as $key => $value) {
            $regions[$value['regionTitle']] = $value['regionTitle'];
        }
        $model = new buyServiceForm();
        if (isset(Yii::app()->session['userAttributes']))
            $model->attributes = Yii::app()->session['userAttributes'];
        $model->city = Yii::app()->params['regions'][Yii::app()->session['userRegion']['id']]['regionTitle'];
        $regionID = Yii::app()->session['userRegion']['id'];
        $tblName = !Yii::app()->user->isGuest ? '_model2serv_all' : '_model2serv_all_new';
        $sql = "SELECT * FROM {{" . $tblName . "}} p WHERE p.\"regionId\" = '" . $regionID . "' AND p.active = 1 AND p.\"modelId\" = " . $data['pageId'] . " ORDER BY p.\"serviceType\", p.sort";
        $groups = array();
        $searches = [];
        $values = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($values as $value) {
            $groups[$value['serviceType']][] = $value;
            $searches[] = array('value' => $value['serviceTitle'], 'url' => $value['serviceId']);
        }

//		$services = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
//        $c = new CDbCriteria();
//        $c->select = '"serviceTitle"';
//        $c->addCondition('"modelId" = ' . $data['pageId'] . ' AND "regionId" = ' . Yii::app()->session['userRegion']['id']);
//        $models = Model2servAll::model()->findAll($c);
//		$services = CHtml::listData($models, 'serviceTitle', 'serviceTitle');
        $catID = Controller::$pageData['_parents']['category']['pageId'];
        foreach (Yii::app()->params['categories'] as $k => $v) {
            if ($v['pageId'] == $catID)
                $randomServices = $v['seoServices'];
        }
//		if (count($services) >= 1) {
//			$c = count($services) >= 4 ? 4 : count($services);
//			$randomServices = array_rand($services, $c);
//			$randomServices = count($randomServices) > 1 ? implode(', ', $randomServices) : $randomServices;
//		}
        $this->pageTitle = 'Ремонт ' . Controller::$pageData['_parents']['brand']['pageTitle'] . ' ' . Controller::$pageData['pageTitle'] . ': ' . mb_strtolower($randomServices, 'utf-8') . ' — Моби03';
        Yii::app()->clientScript->registerMetaTag('Моби03 предоставляет следующие услуги по ремонту ' . Controller::$pageData['_parents']['brand']['pageTitle'] . ' ' . Controller::$pageData['pageTitle'] . ': ' . mb_strtolower($randomServices, 'utf-8') . ' и другие.', 'description');
        Yii::app()->clientScript->registerMetaTag('качественный ремонт ' . Controller::$pageData['_parents']['brand']['pageTitle'] . ' ' . Controller::$pageData['pageTitle'] . ' с гарантией', 'keywords');
        $file = Yii::app()->basePath . '/../uploads/currency.txt';
        $exchange = file_exists($file) ? file_get_contents($file) : 0;
        $this->render('model', array('data' => $data, 'searches' => $searches, 'groups' => $groups, 'model' => $model, 'regions' => $regions, 'exchange' => $exchange
//                    'services' => $services
        ));
    }

}
